<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';

defineProps({
  msg: String,
})

const count = ref(0)


onMounted(() => {
const form = document.getElementById('control-row');
const input = document.getElementById('input');
const message = document.getElementById('message');

// The async IIFE is necessary because Chrome <89 does not support top level await.
(async function initPopupWindow() {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  if (tab?.url) {

    try {
      let url = new URL(tab.url);
      input.value = url.hostname;
    } catch {
      // ignore
    }

  }

  input.focus();
})();

form.addEventListener('submit', handleFormSubmit);

async function handleFormSubmit(event) {
  event.preventDefault();

  clearMessage();

  let url = stringToUrl(input.value);
  if (!url) {
    setMessage('Invalid URL');
    return;
  }




  console.log(url.hostname)
  let cookies = await getDomainCookies(url.hostname);
    let cookie = '';
   cookies.forEach(c=>{
	 cookie = cookie+`${c.name}=${c.value};`
   })

   setMessage(JSON.stringify(cookies));
   console.log(cookie)
   let message = await  getSite(input.value,cookie);
  setMessage(message);

    console.log(message)
let data =  parseSite(message);
   console.log(data)
   setMessage(data);
}

function stringToUrl(input) {
  // Start with treating the provided value as a URL
  try {
    return new URL(input);
  } catch {
    // ignore
  }
  // If that fails, try assuming the provided input is an HTTP host
  try {
    return new URL('http://' + input);
  } catch {
    // ignore
  }
  // If that fails ¯\_(ツ)_/¯
  return null;
}

async function getDomainCookies(domain) {

  let cookies = [];
  try {
     cookies = await chrome.cookies.getAll({ domain });

  } catch (error) {
    return `Unexpected error: ${error.message}`;
  }
  return cookies;
}


async function getSite(url,cookies) {
  // 创建其他的实例发送网络请求
	const instance1 = axios.create({
		//baseURL: "",
		timeout: 6000,
		headers: {'cookies':cookies}
	})

  let html = {};
  try {
     html = await instance1.get(url);

  } catch (error) {
    return `Unexpected error: ${error.message}`;
  }

  return html.data;
}

function parseSite(doc) {
	//const parser = new DOMParser();
	//const doc = parser.parseFromString(html, "text/html");

	//商品标题
	var title = doc.getElementsByClassName('title-text')[0].innerHTML;
	console.log(title)

	//商品sku
	var skus = [];
	var $skus = doc.getElementsByClassName('sku-item-left');
	for (let index = 0; index < $skus.length; index++) {
		skus.push(
		{name:$skus[index].getElementsByClassName('sku-item-name')[0].innerText
		,price:$skus[index].getElementsByClassName('discountPrice-price')[0].innerText
		,num:$skus[index].getElementsByClassName('sku-item-sale-num')[0].innerText})
	}
	console.log(skus)

	//商品图片
	var galleryImgs = [];
	var $gallery = doc.getElementsByClassName('detail-gallery-img')
	for(var i = 0; i < $gallery.length; i++){
		galleryImgs.push( $gallery[i].src);
	};
	console.log(galleryImgs)

	//商品参数
	var attrs = [];
	var $attrs = doc.getElementsByClassName('offer-attr-list')[1].getElementsByClassName('offer-attr-item');
	for (let index = 0; index < $attrs.length; index++) {
		attrs.push( {name:$attrs[index].firstChild.innerText,value:$attrs[index].lastChild.innerText});
	}
	console.log(attrs)

	//商品详情图
	var detailImgs = [];
	var $detailImgs = doc.getElementsByClassName('content-detail')[0].getElementsByTagName('img');
	for (let index = 0; index < $detailImgs.length; index++) {
		detailImgs.push($detailImgs[index].src);
	}
	console.log(detailImgs)
	return {title,skus,galleryImgs,attrs,detailImgs}
}


function setMessage(str) {
  message.textContent = str;
  message.hidden = false;
}

function clearMessage() {
  message.hidden = true;
  message.textContent = '';
}
})

</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <button type="button" @click="count++">count is {{ count }}</button>


   <form id="control-row">
      <label for="input">Domain:</label>
      <input type="text" id="input" />
      <br />
      <button id="go">Load Cookies</button>
    </form>
    <span id="message" hidden></span>


  </div>


</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
